package com.jyw.business.knowledge.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyw.business.knowledge.domain.KlKnowledge;
import com.jyw.business.knowledge.domain.dto.*;
import com.jyw.business.knowledge.domain.vo.KlKnowledgeVo;
import com.jyw.business.knowledge.enums.KnowledgeApplyStatus;
import com.jyw.business.knowledge.mapper.KlKnowledgeMapper;
import com.jyw.business.knowledge.service.IKlKnowledgeService;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.SecurityUtils;
import com.jyw.system.domain.SysKnowledgeReviewConfig;
import com.jyw.system.domain.vo.SysKnowledgeReviewDetailVo;
import com.jyw.system.service.ISysKnowledgeReviewConfigService;
import com.jyw.system.utils.ConversionUtil;
import com.jyw.system.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 知识库-信息Service业务层处理
 *
 * @author zhangcheng
 * @date 2023-11-17
 */
@Service
public class KlKnowledgeServiceImpl extends ServiceImpl<KlKnowledgeMapper, KlKnowledge> implements IKlKnowledgeService {
    @Resource
    private KlKnowledgeMapper klKnowledgeMapper;

    @Resource
    private ISysKnowledgeReviewConfigService sysKnowledgeReviewConfigService;

    @Override
    public List<KlKnowledgeVo> getApplyList(KlKnowledgePageDto pageDto) {
        List<KlKnowledgeVo> list=klKnowledgeMapper.getApplyList(pageDto);
        if(CollUtil.isNotEmpty(list)){
            Long userId=pageDto.getUserId();
            List<KlKnowledgeVo> newList= ConversionUtil.conversionList(list,KlKnowledgeVo.class);
            newList.forEach(klKnowledgeVo -> {
                // 设置附件
                klKnowledgeVo.setEnclosure(FileUtils.IdToFile(klKnowledgeVo.getEnclosureId()));
                if(!ObjectUtils.isEmpty(klKnowledgeVo.getCreateUser()) &&klKnowledgeVo.getCreateUser().equals(userId)){
                    klKnowledgeVo.setApplicant(true);
                }else{
                    klKnowledgeVo.setApplicant(false);
                }
                if(pageDto.getIsAdmin()!=null&&pageDto.getIsAdmin()){
                    klKnowledgeVo.setReviewer(true);
                }else{
                    boolean reviewer=false;
                    if(StrUtil.isNotEmpty(klKnowledgeVo.getReviewUserIds())){
                        String reviewUserIds=klKnowledgeVo.getReviewUserIds();
                        if(reviewUserIds.contains(String.valueOf(userId))){
                            reviewer=true;
                        }
                    }
                    klKnowledgeVo.setReviewer(reviewer);
                }
            });
            return newList;
        }
        return Collections.emptyList();
    }

    @Override
    public List<KlKnowledgeVo> getPassList(KlKnowledgePageDto pageDto) {
        // 查询审核通过的
        pageDto.setApplyStatus(KnowledgeApplyStatus.PASS.getValue());
        List<KlKnowledgeVo> list=klKnowledgeMapper.getPassList(pageDto);
        if(CollUtil.isNotEmpty(list)){
            Long userId=pageDto.getUserId();
            List<KlKnowledgeVo> newList= ConversionUtil.conversionList(list,KlKnowledgeVo.class);
            newList.forEach(klKnowledgeVo -> {
                // 设置附件
                klKnowledgeVo.setEnclosure(FileUtils.IdToFile(klKnowledgeVo.getEnclosureId()));
                klKnowledgeVo.setApplicant(false);
                if(pageDto.getIsAdmin()!=null&&pageDto.getIsAdmin()){
                    klKnowledgeVo.setReviewer(true);
                }else{
                    boolean reviewer=false;
                    if(StrUtil.isNotEmpty(klKnowledgeVo.getReviewUserIds())){
                        String reviewUserIds=klKnowledgeVo.getReviewUserIds();
                        if(reviewUserIds.contains(String.valueOf(userId))){
                            reviewer=true;
                        }
                    }
                    klKnowledgeVo.setReviewer(reviewer);
                }
            });
            return newList;
        }
        return Collections.emptyList();
    }

    @Override
    public List<KlKnowledgeVo> getListByKeyword(String keyword) {
        List<KlKnowledgeVo> list=klKnowledgeMapper.getListByKeyword(keyword);
        if(CollUtil.isNotEmpty(list)) {
            List<KlKnowledgeVo> newList = ConversionUtil.conversionList(list, KlKnowledgeVo.class);
            return newList;
        }
        return null;
    }

    @Override
    public KlKnowledgeVo getInfoById(Long id) {
        KlKnowledge klKnowledge=this.getById(id);
        if(klKnowledge!=null){
            KlKnowledgeVo klKnowledgeVo=BeanUtil.toBean(klKnowledge,KlKnowledgeVo.class);
            // 设置附件
            klKnowledgeVo.setEnclosure(FileUtils.IdToFile(klKnowledgeVo.getEnclosureId()));
            return ConversionUtil.conversion(klKnowledgeVo,KlKnowledgeVo.class);
        }
        return null;
    }

    @Override
    public void add(KlKnowledgeAddDto addDto, Long createUser) {
        KlKnowledge klKnowledge = BeanUtil.copyProperties(addDto, KlKnowledge.class);
        klKnowledge.setCreateUser(createUser);
        // 设置附件
        klKnowledge.setEnclosureId(FileUtils.fileToId(addDto.getEnclosure()));
        // 设置审核状态
        getApplyStatus(klKnowledge);
        this.save(klKnowledge);
    }

    /**
     * 设置审核状态
     *
     * @param klKnowledge
     */
    private void getApplyStatus(KlKnowledge klKnowledge){
        if(klKnowledge.getState()==null){
            klKnowledge.setState(1);
        }
        if(StrUtil.isEmpty(klKnowledge.getApplyStatus())){
            klKnowledge.setApplyStatus(KnowledgeApplyStatus.SUBMIT_TO.getValue());
        }
        // 提交状态下判断
        if(klKnowledge.getApplyStatus().equals(KnowledgeApplyStatus.AUDIT.getValue())){
            SysKnowledgeReviewDetailVo reviewConfig=sysKnowledgeReviewConfigService.getDefaultConfig();
            klKnowledge.setSubmitUser(SecurityUtils.getUserId());
            klKnowledge.setCreateTime(LocalDateTime.now());
            // 启用状态下设置 审核人
            if(reviewConfig!=null&&reviewConfig.getEnabled()){
                if(StrUtil.isNotEmpty(klKnowledge.getFaultType())){
                    String faultType=klKnowledge.getFaultType();
                    SysKnowledgeReviewConfig knowledgeReview =sysKnowledgeReviewConfigService.findByFaultType(faultType);
                    if(knowledgeReview!=null&&StrUtil.isNotEmpty(knowledgeReview.getReviewUserIds())){
                        klKnowledge.setReviewUserIds(knowledgeReview.getReviewUserIds());
                    }
                }
            }else{
                // 未启用审核 直接通过
                klKnowledge.setApplyStatus(KnowledgeApplyStatus.PASS.getValue());
            }
        }
    }

    @Override
    public void edit(KlKnowledgeEditDto editDto,Long userId) {
        KlKnowledge klKnowledge = this.getById(editDto.getId());
        if (klKnowledge != null) {
            BeanUtil.copyProperties(editDto, klKnowledge);
            // 设置附件
            klKnowledge.setEnclosureId(FileUtils.fileToId(editDto.getEnclosure()));
            // 设置审核状态
            getApplyStatus(klKnowledge);
            klKnowledge.setUpdateUser(userId);
            klKnowledge.setUpdateTime(LocalDateTime.now());
            this.updateById(klKnowledge);
        }else{
            throw new ServiceException("编辑数据不存在");
        }
    }

    @Override
    public void editPass(KlKnowledgeEditPassDto editDto, Long userId) {
        KlKnowledge klKnowledge = this.getById(editDto.getId());
        if (klKnowledge != null) {
            BeanUtil.copyProperties(editDto, klKnowledge);
            // 设置附件
            klKnowledge.setEnclosureId(FileUtils.fileToId(editDto.getEnclosure()));
            klKnowledge.setUpdateUser(userId);
            klKnowledge.setUpdateTime(LocalDateTime.now());
            this.updateById(klKnowledge);
        }else{
            throw new ServiceException("编辑数据不存在");
        }
    }

    @Override
    public void editState(KlKnowledgeStateDto stateDto) {
        KlKnowledge klKnowledge = this.getById(stateDto.getId());
        if (klKnowledge != null) {
            klKnowledge.setState(stateDto.getState());
            this.updateById(klKnowledge);
        }else{
            throw new ServiceException("编辑数据不存在");
        }
    }

    @Override
    public void pass(KlKnowledgePassDto passDto, Long userId) {
        KlKnowledge klKnowledge = this.getById(passDto.getId());
        if (klKnowledge != null) {
            BeanUtil.copyProperties(passDto, klKnowledge);
            klKnowledge.setApplyUserId(userId);
            klKnowledge.setApplyStatus(KnowledgeApplyStatus.PASS.getValue());
            klKnowledge.setApplyTime(LocalDateTime.now());
            if(passDto.getIsEdit()!=null&&passDto.getIsEdit()){
                klKnowledge.setUpdateUser(userId);
                klKnowledge.setUpdateTime(LocalDateTime.now());
            }
            this.updateById(klKnowledge);
        }else{
            throw new ServiceException("操作数据不存在");
        }
    }

    @Override
    public void reject(KlKnowledgeRejectDto editDto,Long userId) {
        KlKnowledge klKnowledge = this.getById(editDto.getId());
        if (klKnowledge != null) {
            BeanUtil.copyProperties(editDto, klKnowledge);
            klKnowledge.setApplyUserId(userId);
            klKnowledge.setApplyStatus(KnowledgeApplyStatus.NOT_PASS.getValue());
            klKnowledge.setApplyTime(LocalDateTime.now());
            this.updateById(klKnowledge);
        }else{
            throw new ServiceException("操作数据不存在");
        }
    }

    @Override
    public int deleteKlKnowledgeByIds(Long[] ids) {
        return klKnowledgeMapper.deleteKlKnowledgeByIds(ids);
    }
}
